const path = require('path')
// const webpack = require('webpack')
const GitRevisionPlugin = require('git-revision-webpack-plugin')
const GitRevision = new GitRevisionPlugin()
const buildDate = JSON.stringify(new Date().toLocaleString())
const createThemeColorReplacerPlugin = require('./config/plugin.config')
// const CompressionPlugin = require('compression-webpack-plugin')
function resolve(dir) {
	return path.join(__dirname, dir)
}

// check Git
function getGitHash() {
	try {
		return GitRevision.version()
	} catch (e) {}
	return 'unknown'
}

const isProd = process.env.NODE_ENV === 'production'

const assetsCDN = {
	// webpack build externals,
	externals: {
		vue: 'Vue',
		'vue-router': 'VueRouter',
		vuex: 'Vuex',
		axios: 'axios',
		moment: 'moment',
		'@antv/data-set': 'DataSet'
	},
	css: [],
	// https://unpkg.com/browse/vue@2.6.10/
	js: [
		// '//cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.min.js',
		// 	'//cdn.jsdelivr.net/npm/vue-router@3.1.3/dist/vue-router.min.js',
		// '//cdn.jsdelivr.net/npm/vuex@3.1.1/dist/vuex.min.js',
		// 	'//cdn.jsdelivr.net/npm/axios@0.19.0/dist/axios.min.js',
		// 	'//cdn.jsdelivr.net/npm/moment@2.29.1/moment.min.js',
		// 	'//cdn.bootcss.com/moment.js/2.24.0/locale/zh-cn.js'
		'./public/tool/vue.min.js',
		'./public/tool/vue-router.min.js',
		'./public/tool/vuex.min.js',
		'./public/tool/axios.min.js',
		'./public/tool/moment.min.js',
		'./public/tool/zh-cn.js',
		'//cdn.jsdelivr.net/npm/@antv/data-set@0.11.8/build/data-set.min.js',
	],
	module: {
		rules: [{
				// 对 vue 文件，使用 cache-loader 进行缓存
				test: /\.vue$/,
				loader: 'vue-loader',
				options: {
					cacheDirectory: path.resolve(__dirname, '../node_modules/.cache/vue-loader'),
					cacheIdentifier: 'cache-loader:{version} {process.env.NODE_ENV}'
				}
			},
			{
				// 对 .js 文件，开启 babel-loader 自带的缓存
				test: /\.js$/,
				exclude: /node_modules/,
				loader: 'babel-loader?cacheDirectory=true'
			}
			// {
			//   // 对图片进行压缩
			//   test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
			//   use: [
			//     {
			//     loader: 'url-loader',
			//     options: {
			//       limit: 10000,
			//       name: 'img/[name].[hash:7].[ext]'
			//       }
			//     },
			//     {
			//       loader: 'image-webpack-loader',
			//       options: {
			//         bypassOnDebug: true
			//       }
			//     }
			//   ]
			// }
		]
		// 其他规则
	}
}

// vue.config.js
const vueConfig = {
	configureWebpack: {
		// webpack plugins,
		plugins: [
			// Ignore all locale files of moment.js
			// new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
			// new webpack.DefinePlugin({
			//   APP_VERSION: `"${require('./package.json').version}"`,
			//   GIT_HASH: JSON.stringify(getGitHash()),
			//   BUILD_DATE: buildDate
			// }),
			// new CompressionPlugin({
			//   algorithm: 'gzip', // 使用gzip压缩
			//   test: /\.js$|\.html$|\.css$/, // 匹配文件名
			//   filename: '[path][base].gz', // 压缩后的文件名(保持原文件名，后缀加.gz)
			//   minRatio: 0.8, // 压缩率小于1才会压缩
			//   threshold: 10240, // 对超过10k的数据压缩
			//   deleteOriginalAssets: false // 是否删除未压缩的源文件，谨慎设置，如果希望提供非gzip的资源，可不设置或者设置为false（比如删除打包后的gz后还可以加载到原始资源文件）
			// })
		],
		// resolve: {
		//   alias: {
		//     '@ant-design/icons/lib/dist$': resolve('./src/core/antd/icons.js')
		//   }
		// },
		// if prod, add externals
		externals: isProd ? assetsCDN.externals : {}
	},
	chainWebpack: config => {
		config.resolve.alias.set('@$', resolve('src'))

		const svgRule = config.module.rule('svg')
		svgRule.uses.clear()
		svgRule
			.oneOf('inline')
			.resourceQuery(/inline/)
			.use('vue-svg-icon-loader')
			.loader('vue-svg-icon-loader')
			.end()
			.end()
			.oneOf('external')
			.use('file-loader')
			.loader('file-loader')
			.options({
				name: 'assets/[name].[hash:8].[ext]'
			})

		// if prod is on
		// assets require on cdn
		if (isProd) {
			config.plugin('html').tap(args => {
				args[0].cdn = assetsCDN
				return args
			})
		}
	},
	css: {
		loaderOptions: {
			less: {
				modifyVars: {
					// less vars，customize ant design theme
					// 'primary-color': '#1890ff',
					// 'link-color': '#1890ff',
					// 'border-radius-base': '2px'
				},
				// DO NOT REMOVE THIS LINE
				javascriptEnabled: true
			}
		}
	},
	devServer: {
		// development server port 8000
		port: 8000,
		hot: true,
		open: true,
		https: true, //线上
		// https: false,//开发
		// If you want to turn on the proxy, please remove the mockjs /src/main.jsL11
		proxy: {
			'/admin': {
				// target: 'https://tcrm.jialexi.top/admin',//开发
				target: 'https://crm.jialexi.top/admin', //线上 
				ws: false,
				changeOrigin: true,
				pathRewrite: {
					'/admin': ''
				}
			}
		}
	},
	// 公共路径(必须有的)
	publicPath: './',
	// 输出文件目录
	outputDir: 'dist',
	// 静态资源存放的文件夹(相对于ouputDir)
	assetsDir: 'static',
	// disable source map in production
	productionSourceMap: false,
	lintOnSave: false,
	// babel-loader no-ignore node_modules/*
	transpileDependencies: []
}

// preview.pro.loacg.com only do not use in your production;
if (process.env.VUE_APP_PREVIEW === 'true') {
	console.log('VUE_APP_PREVIEW', true)
	// add `ThemeColorReplacer` plugin to webpack plugins
	vueConfig.configureWebpack.plugins.push(createThemeColorReplacerPlugin())
}

module.exports = vueConfig